﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DHQGHN.Common;
using DHQGHN.DAL.BO.Admin;
using DHQGHN.DAL.Common;
using DHQGHN.MVC.Controllers;
using DHQGHN.PM0.Common.Attributes;
using DHQGHN.PM0.Models.Admin;
//using DHQGHN.DAL.Models.Admin;

namespace DHQGHN.PM0.Controllers.Admin
{
    public class OccupationController : BaseController
    {
        OccupationBO occBO;
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(OccupationController));
        // GET: /Application/
        public ActionResult Index()
        {
            try
            {
                ViewBag.ActiveMenus = ViewBag.ActiveMenus == null ? new System.Collections.Hashtable() : ViewBag.ActiveMenus;
                ViewBag.ActiveMenus[13] = "active";
                ViewBag.ActiveMenus[16] = "active";
                OccupationModel aModel = new OccupationModel { CODE = null, NAME = null, DELETED = 2 };
                var model = search(aModel, 0, null);
                return View("~/Views/Occupation/Occupation.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// <summary>
        /// Hiển thị form thêm mới người dùng
        /// </summary>
        /// <param name="occupationId"></param>
        /// <returns></returns>
        [HttpPost]
        //[CustomAuthorize]
        //[ActionDescription(ActionCode = WebConst.ACTION_USER_ADD_CODE, ActionName = WebConst.ACTION_USER_ADD_NAME, GroupName = WebConst.USERS_GROUP_NAME, GroupCode = WebConst.USERS_GROUP_CODE, IsMenu = false)]
        public ActionResult actionPrepareCreateOrUpdateOccupation(string occupationId)
        {
            try
            {
                OccupationModel occModel = null;
                if (!String.IsNullOrEmpty(occupationId))
                {
                    occBO = new OccupationBO();
                    occModel = new OccupationModel(occBO.GetOcById(occupationId));
                }
                if (occModel == null)
                {
                    occModel = new OccupationModel();
                }

                occModel.lstParent = getListParent();

                if (Request.IsAjaxRequest())
                {
                    return PartialView("~/Views/Occupation/_OccupationModel.cshtml", occModel);
                }
                //RedirectToAction("ManageUsers", "Admin");
                return View(occModel);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpPost]
        public ActionResult actionSearch(OccupationModel aModel = null, int pageIndex = 0, string sort = "AppId", string sortDir = "ASC", string currentId = null)
        {
            try
            {
                if (aModel == null) aModel = new OccupationModel();
                
                var model = search(aModel, pageIndex, currentId);
                return PartialView("~/Views/Occupation/_OccupationList.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// <summary>
        /// Thêm mới người dùng
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        //[ActionDescription(ActionCode = WebConst.ACTION_USER_ADD_CODE, ActionName = WebConst.ACTION_USER_ADD_NAME, GroupName = WebConst.USERS_GROUP_NAME, GroupCode = WebConst.USERS_GROUP_CODE, IsMenu = false)]
        public ActionResult actionCreateOrUpdateOccupation(OccupationModel model)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    occBO = new OccupationBO();
                    bool result = occBO.createOrUpdateOccupation(model.toDALModel());
                    if (result)
                    {
                        LogStream.Write<OccupationModel>(GetCurrentUserName(),
                                               CommonData.AppName,
                                               GetFunction(),
                                               Resources.Localization.ActionSaveUpdateCaption + " - actionCreateOrUpdateOccupation", model);

                        return Json(JsonResponse.Json200(Resources.Localization.Confirm_Save_Success));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500(Resources.Localization.Confirm_Save_Error));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        public ActionResult actionDelete(string[] ids)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    occBO = new OccupationBO();
                    bool result = occBO.deleteOccupation(ids);

                    if (result)
                    {
                        LogStream.Write(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            CommonData.GetListId(ids),
                            Resources.Localization.ActionDeleteCaption + " - actionDelete");

                        return Json(JsonResponse.Json200(Resources.Localization.Confirm_Delete_Success));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500(Resources.Localization.Confirm_Save_Error));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        public ActionResult actionActive(string occId)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    occBO = new OccupationBO();
                    bool result = true;
                    OccupationModel occModel = new OccupationModel(occBO.GetOcById(occId));
                    occModel.DELETED = 0;
                    occBO.createOrUpdateOccupation(occModel.toDALModel());
                    if (result)
                    {
                        LogStream.Write(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            CommonData.GetListId(new string[] { occId }),
                            Resources.Localization.ActionActiveCaption + " - actionActive");

                        return Json(JsonResponse.Json200(Resources.Localization.Confirm_Save_Success));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500(Resources.Localization.Confirm_Save_Error));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        /// <summary>
        /// Kiem tra xem ten ung dung da ton tai chua
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="OCCUPATION_ID"> </param>
        /// <returns></returns>
        public JsonResult CheckExistOcName(string Name, string OCCUPATION_ID)
        {
            try
            {
                OccupationModel appModel = new OccupationModel()
                {
                    NAME = Name.Trim()

                };
                var model = search(appModel, 0, "-1");
                var isExist = false;
                if (model.Data.Any())
                {
                    var lstItem = model.Data;
                    foreach (OccupationModel app in lstItem)
                    {
                        if (!String.IsNullOrEmpty(Name.Trim()) && Name.Trim().ToUpper().Equals(app.NAME.Trim().ToUpper()) && !app.OCCUPATION_ID.Equals(OCCUPATION_ID))
                        {
                            isExist = true;
                            break;
                        }
                    }
                }
                if (isExist)
                {
                    return Json(Resources.Localization.OcNameExist);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// <summary>
        /// Kiem tra xem Ma ung dung da ton tai chua
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="OCCUPATION_ID"> </param>
        /// <returns></returns>
        public JsonResult CheckExistOcCode(string Code, string OCCUPATION_ID)
        {
            try
            {
                OccupationModel appModel = new OccupationModel()
                {
                    CODE = Code.Trim()
                };
                var model = search(appModel, 0, "-1");
                var isExist = false;
                if (model.Data.Any())
                {
                    var lstItem = model.Data;
                    foreach (OccupationModel app in lstItem)
                    {
                        if (!String.IsNullOrEmpty(Code.Trim()) && Code.Trim().ToUpper().Equals(app.CODE.Trim().ToUpper()) && !app.OCCUPATION_ID.Equals(OCCUPATION_ID))
                        {
                            isExist = true;
                            break;
                        }
                    }
                }
                if (isExist)
                {
                    return Json(Resources.Localization.OcCodeExist);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private DataPage<OccupationModel> search(OccupationModel aModel, int pageIndex, string currentId)
        {
            try
            {
                occBO = new OccupationBO();
                var DALModel = occBO.GetDynamicListPaging(aModel.toDALModel(), PageSize, pageIndex);
                var model = new DataPage<OccupationModel>();
                var lstItem = DALModel.Data;
                foreach (DHQGHN.DAL.Models.Admin.OccupationModel app in lstItem)
                {
                    model.Data.Add(new OccupationModel(app));
                }

                OccupationModel appModel = null;
                if (Convert.ToInt32(currentId) >= 0 && model.Data.Count > 0)
                {
                    appModel = model.Data.Find(user => user.OCCUPATION_ID == currentId);
                    model.CustomData = appModel;
                }
                else
                {
                    model.CustomData = aModel;
                }
                if (model.Data.Count > 0)
                {
                    //Tao component phan trang
                    var pagNative = new Pagination
                    {
                        ActionName = "actionSearch",
                        ModelName = "Occupation",
                        CurrentPage = pageIndex,
                        InputSearchId = string.Empty,
                        TagetReLoadId = "occ-list",

                    };
                    pagNative.TotalRows = model.Data[0].RecordCount;
                    pagNative.CurrentRow = model.Data.Count;
                    ViewBag.Pagination = pagNative;
                }
                return model;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private SelectList getListParent()
        {
            try
            {
                occBO = new OccupationBO();
                var lstParent = occBO.GetAll();
                List<SelectListItem> lstItems = new List<SelectListItem>();
                lstItems.Add(new SelectListItem
                {
                    Value = "-1",
                    Text = string.Empty
                });
                foreach (var p in lstParent)
                {
                    lstItems.Add(new SelectListItem
                    {
                        Value = p.CODE,
                        Text = p.CODE + " - " + p.NAME
                    });
                }

                return new SelectList(lstItems, "Value", "Text");
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private string GetFunction()
        {
            return "Danh mục nghề nghiệp - OccupationController";
        }
    }
}